import { createDecorator } from '../core/helpers'
import { isFunction, isString } from '@gowiny/js-utils';
import { Vue } from '../core/vue';

interface Params{
    name?:string,
    dest?:any
}

function getDest(params:Params,defVal?:any){
    let dest = params.dest || defVal || Vue.defaultStore || {};
    if(isFunction(dest)){
        dest = dest();
    }
    return dest;
}


function create(params:Params,target: any, propertyKey: string,descriptor?: PropertyDescriptor){
    createDecorator(function (ctx, key) {
        const options = ctx.options
        options.computed = options.computed || {}
        const name = params.name || key;
        if(Vue.storeType == 'vuex'){
            options.computed[key] = function() {
                const getter = this.$store.getters[name];
                return getter
            }
        }else{
            options.computed[key] = function() {
                const result = getDest(params)[name];
                return result
            }
        }
        

    })(target, propertyKey);
}

export function Getter(params:string):any;
export function Getter(dest:any,params?:string):any;
export function Getter(target: any, propertyKey: string):void;
export function Getter(target: any, propertyKey: string,descriptor: PropertyDescriptor):void;
export function Getter(...args:any[]):void | any{
    if(args.length > 0 && args[0] instanceof Vue){//装饰器
        create({
            name:args[1]
        },args[0],args[1],args[2])
    }else{//装饰器工厂
        return function (target: any, propertyKey: string,descriptor?: PropertyDescriptor) {

            const params:Params = {

            };
            if(args.length > 0){
                if(isString(args[0])){
                    params.name = args[0];
                }else{
                    params.dest = args[0];
                    if(args.length > 1){
                        params.name = args[1];
                    }
                }
            }
            if(!params.name){
                params.name = propertyKey
            }
            create(params,target,propertyKey,descriptor)
        };
    }
}
